package com.ljh.myrpc.Proxy;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

@Slf4j
public class MockServiceProxy implements InvocationHandler {
    /**
     * 调用代理
     * 主要用途是模拟服务调用（Mock），在没有实际实现的情况下，返回默认值以便进行测试或占位
     * @return
     * @throws Throwable
     */

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Class<?> returnType = method.getReturnType();
        log.info("mock invoke {},{}", method.getName(), returnType);

        return getDefaultObject(returnType);
    }

    /**
     * 生成指定类型的默认对象
     * @param returnType
     * @return
     */
    private Object getDefaultObject(Class<?> returnType) {
        // 基本类型
        if(returnType.isPrimitive()){
            if (returnType == boolean.class) {
                return false;
            } else if (returnType == byte.class) {
                return (byte) 0;
            } else if (returnType == short.class) {
                return (short) 0;
            } else if (returnType == int.class) {
                return 0;
            } else if (returnType == long.class) {
                return 0L;
            } else if (returnType == float.class) {
                return 0.0f;
            } else if (returnType == double.class) {
                return 0.0d;
            } else if (returnType == char.class) {
                return '\u0000';
            }
        }
        // 基本类型
        return null;
    }
}
